<?php

/**
 * User: hitman
 * Date: 07/12/2017
 * Time: 10:22 AM
 */

namespace Hitman\SMS\Aliyun;

class Aliyun
{
    protected $accessKey;
    protected $secretKey;
    protected $signName;
    protected $templateCode;

    public function __construct($config)
    {
        $this->accessKey = $config['access_key'];
        $this->secretKey = $config['secret_key'];
        $this->signName = array_get($config, 'sign_name');
        $this->templateCode = array_get($config, 'template_code');
    }

    public function send($phone, $templateParam, $config=null)
    {

        $params = array();

        $accessKeyId     = $this->accessKey;
        $accessKeySecret = $this->secretKey;

        $params["PhoneNumbers"] = $phone;
        $params["SignName"] = array_get($config, 'sign_name') ?: $this->signName;
        $params["TemplateCode"] = array_get($config, 'template_code') ?: $this->templateCode;
        $params['TemplateParam'] = $templateParam;

        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"]);
        }

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action"   => "SendSms",
                "Version"  => "2017-05-25",
            ))
        );

        return $content;
    }
}